package com.jymj.controller;

import com.jymj.common.annotation.SysLog;
import com.jymj.common.validator.Assert;
import com.jymj.common.validator.ValidatorUtils;
import com.jymj.common.validator.group.AddGroup;
import com.jymj.common.validator.group.UpdateGroup;
import com.jymj.entity.SysUserEntity;
import com.jymj.entity.SysXzqEntity;
import com.jymj.service.SysUserRoleService;
import com.jymj.service.SysUserService;
import com.jymj.service.SysXzqService;
import com.jymj.utils.*;
import org.apache.commons.lang.ArrayUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 系统用户
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2016年10月31日 上午10:40:10
 */
@RestController
@RequestMapping("/sys/user")
public class SysUserController extends AbstractController {
    
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysXzqService xzqService;

    /**
     * 所有用户列表
     *
     * @param params
     * @return
     */
    @RequestMapping("/list")
    @RequiresPermissions("sys:user:list")
    public R list(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Long createUserId = null;
        if (params.get("createUserId") != null){
            createUserId = Long.valueOf(params.get("createUserId").toString());
        }
        Query query = new Query(params);
        query.put("createUserId",createUserId);
        List<SysUserEntity> userList = sysUserService.queryList(query);
        int total = sysUserService.queryTotal(query);
        
        PageUtils pageUtil = new PageUtils(userList, total, query.getLimit(), query.getPage());
        
        return R.ok().put("page", pageUtil);
    }

    /**
     * 导出用户信息excel
     * @param response
     */
    @PostMapping("/getUserInfo")
    public R getUserInfo(HttpServletResponse response,String code) throws FileNotFoundException {
        String url = sysUserService.getUserInfo(response, code);
        Map<String, Object> map = new HashMap<>();
        map.put("url", url);
        return R.ok().put("data", map);
    }

    /**
     * 获取登录的用户信息
     *
     * @return
     */
    @RequestMapping("/info")
    public R info() {
        return R.ok().put("user", getUser());
    }

    /**
     * 修改登录用户密码
     *
     * @param password
     * @param newPassword
     * @return
     */
    @SysLog("修改密码")
    @RequestMapping("/password")
    public R password(String password, String newPassword) {
        Assert.isBlank(newPassword, "新密码不为能空");

        //sha256加密
        password = new Sha256Hash(password).toHex();
        //sha256加密
        newPassword = new Sha256Hash(newPassword).toHex();

        //更新密码
        int count = sysUserService.updatePassword(getUserId(), password, newPassword);
        if (count == 0) {
            return R.error("原密码不正确");
        }

        //退出
        ShiroUtils.logout();
        
        return R.ok();
    }
    
    @RequestMapping("/restpassword")
    public Map restpassword(String username, String password, String newPassword, String deviceCode) {
        Map<String, Object> map = new HashMap<>();
        //sha256加密
        password = new Sha256Hash(password).toHex();
        //sha256加密
        newPassword = new Sha256Hash(newPassword).toHex();
        SysUserEntity userEntity = sysUserService.queryByUserName(username);
        if (userEntity == null) {
            map.put("code", 501);
            map.put("msg", "用户名或密码不正确");
            return map;
        } else {
            if (!password.equals(userEntity.getPassword())) {
                map.put("code", 502);
                map.put("msg", "用户名或密码错误！");
                return map;
            }
        }
        if (deviceCode == null || deviceCode.equals("")) {
            map.put("code", 503);
            map.put("msg", "获取机器码失败！");
            return map;
        } else {
            if (userEntity.getDeviceCode() != null && !userEntity.getDeviceCode().equals("")) {
                if (!deviceCode.equals(userEntity.getDeviceCode())) {
                    map.put("code", 504);
                    map.put("msg", "机器码错误！");
                    return map;
                }
            } else {
                map.put("code", 505);
                map.put("msg", "获取机器码失败！");
                return map;
            }
        }
        //更新密码
        int count = sysUserService.updatePassword(userEntity.getUserId(), password, newPassword);
        if (count == 0) {
            map.put("code", 502);
            map.put("msg", "修改失败！");
            return map;
        }
        map.put("code", 0);
        map.put("msg", "修改成功！");
        return map;
    }

    /**
     * 用户信息
     *
     * @param userId
     * @return
     */
    @RequestMapping("/info/{userId}")
    @RequiresPermissions("sys:user:info")
    public R info(@PathVariable("userId") Long userId) {
        SysUserEntity user = sysUserService.queryObject(userId);

        //获取用户所属的角色列表
        List<Long> roleIdList = sysUserRoleService.queryRoleIdList(userId);
        user.setRoleIdList(roleIdList);
        //获取用户所属的行政区
        List<SysXzqEntity> xzqList = new ArrayList<>();
        if (user.getType() != null && (user.getType() == 1 || user.getType() == 4)) {
            xzqList = xzqService.getUserDistrictList(user.getUserId());
        } else if (user.getType() != null && user.getType() == 2 ) {
            xzqList = xzqService.getUserTownList(user.getUserId());
        } else {
            xzqList = xzqService.getUserXzqList(user.getUserId());
        }
        if (xzqList.size() > 0) {
            if (xzqList.get(0).getCode() != null) {
                user.setCode(xzqList.get(0).getCode());
            }
            if (xzqList.get(0).getName() != null) {
                user.setXzqmc(xzqList.get(0).getName());
            }
            if (xzqList.get(0).getCenter() != null) {
                user.setCenter(xzqList.get(0).getCenter());
            }
            if (xzqList.get(0).getParentName() != null){
                user.setZhen(xzqList.get(0).getParentName());
            }
        }
        return R.ok().put("user", user);
    }

    //事务控制方法
    @Autowired
    private PlatformTransactionManager platformTransactionManager;
    /**
     * 保存用户
     *
     * @param user
     * @return
     */
    @SysLog("保存用户")
    @RequestMapping("/save")
    @RequiresPermissions("sys:user:save")
    public R save(@RequestBody SysUserEntity user) {
        //事务控制创建一个默认的事务控制类
        DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
        definition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus status = platformTransactionManager.getTransaction(definition);
        try {
            ValidatorUtils.validateEntity(user, AddGroup.class);
            user.setCreateUserId(getUserId());
            sysUserService.save(user);
            //事务完成提交
            platformTransactionManager.commit(status);
            return R.ok();
        } catch (RRException ex) {
            logger.error(ex.getMessage(), ex);
            //事务回滚
            platformTransactionManager.rollback(status);
            throw new RRException(ex.getMsg());
        }
    }

    /**
     * 修改用户
     *
     * @param user
     * @return
     */
    @SysLog("修改用户")
    @RequestMapping("/update")
//    @RequiresPermissions("sys:user:update")
    public R update(@RequestBody SysUserEntity user) {
        ValidatorUtils.validateEntity(user, UpdateGroup.class);

        //user.setCreateUserId(getUserId());
        sysUserService.update(user);
        
        return R.ok();
    }

    /**
     * 删除用户
     *
     * @param userIds
     * @return
     */
    @SysLog("删除用户")
    @RequestMapping("/delete")
    @RequiresPermissions("sys:user:delete")
    public R delete(@RequestBody Long[] userIds) {
        if (ArrayUtils.contains(userIds, 1L)) {
            return R.error("系统管理员不能删除");
        }
        
        if (ArrayUtils.contains(userIds, getUserId())) {
            return R.error("当前用户不能删除");
        }
        
        sysUserService.deleteBatch(userIds);
        
        return R.ok();
    }

    /**
     * 所有用户列表
     *
     * @param pid
     * @return
     */
    @RequestMapping("/linkpsn/{pid}")
    public R list(@PathVariable("pid") Long pid) {
        List<SysUserEntity> userList = sysUserService.queryAll(pid, getUserId());
        return R.ok().put("userList", userList);
    }

    /*
    * 手机端 保存用户  角色  行政区  菜单 关系表
    * */
    @SysLog("保存用户")
    @RequestMapping("/saveUser")
    public R saveUser(@RequestBody SysUserEntity user) {
        try {
            ValidatorUtils.validateEntity(user, AddGroup.class);
            user.setCreateUserId(getUserId());
            sysUserService.saveUser(user);
            return R.ok();
        } catch (RRException ex) {
            logger.error(ex.getMessage(), ex);
            return R.error();
        }
    }

    /*
    * 查询 村镇内人员  参数 code  name(模糊查)
    * */
    @RequestMapping("/queryRy")
    public R queryRy(String code,String name){
        List<SysUserEntity> sysUserEntities = sysUserService.queryRy(code,name);
        return R.ok().put("data",sysUserEntities);
    }

    /*
    * 手机端 修改用户
    * */
    @RequestMapping("/updateUser")
    public R updateUser(@RequestBody SysUserEntity user){
        ValidatorUtils.validateEntity(user, UpdateGroup.class);

        sysUserService.updateUser(user);
        return R.ok();
    }

    @PostMapping("/updateUserInfo")
    public R updateUserInfo(@RequestBody SysUserEntity sysUserEntity){
        sysUserService.updateUserInfo(sysUserEntity);
        return R.ok("修改成功");
    }
}
